<?php


namespace app\subscribe;

use app\model\GroupUser;
use GatewayWorker\Lib\Gateway;

class User
{
    public function onUserLogin($user)
    {
        if ($user['token']) {//验证token的合法性
            $token = strtr($user['token'], [' ' => '+']);
            if ($userData = \xy_jx\Utils\Encryption::decrypt($token)) {
                //判断token 是否正确
                $redis = \Utils::redis();
                if ($token != $redis->get('Account:token_' . $userData['uid']))
                    Gateway::closeClient($user['client_id']);

                //web_worker 流程
                Gateway::$registerAddress = config('gateway_worker.registerAddress');
                Gateway::bindUid($user['client_id'], $userData['uid']);
                // 用户登录后加入已在的房间
                if ($group_id = GroupUser::where('uid', $userData['uid'])->where('df', 0)->column('group_id')) {
                    foreach ($group_id as $value) {
                        Gateway::joinGroup($user['client_id'], $value);
                    }
                }
                Gateway::sendToClient($user['client_id'], json_encode(
                        [
                            'type' => 'onConnect',
                            'id' => $user['client_id'],
                            'data' => [],
                        ]
                    )
                );
            } else {
                Gateway::closeClient($user['client_id']);
            }
        } else {
            Gateway::closeClient($user['client_id']);
        }
    }
}
